package com.example.easyscript.bean.task;

import cn.hutool.extra.cglib.CglibUtil;
import com.example.easyscript.bean.BaseBean;
import com.example.easyscript.enums.EnumUtils;
import com.example.easyscript.enums.TaskStatusEnum;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.*;

@Data
public class TaskBean extends BaseBean {

    @ApiModelProperty("任务名称")
    private String taskName;

    @ApiModelProperty("任务描述")
    private String taskDesc;

    @ApiModelProperty("任务窗口名")
    private String windowsName;

    @ApiModelProperty("状态图")
    private StateDiagram stateDiagram;

    @ApiModelProperty("操作集")
    private Map<Integer, OperationBean> operationBeanMap;

    @ApiModelProperty("现实状态")
    private Integer currentStateSeq;

    @ApiModelProperty("当前目标状态序号")
    private Integer targetStateSeq;

    @ApiModelProperty("当前操作序号")
    private Integer targetOperationSeq;

    @ApiModelProperty("当前步骤序号")
    private Integer targetStepSeq;

    @ApiModelProperty("需要执行的操作列表")
    private LinkedList<OperationBean> operationQue;

    @ApiModelProperty("任务执行状态")
    private TaskStatusEnum status;

    @ApiModelProperty("正在运行的操作")
    private OperationBean currentOperationBean;

    @ApiModelProperty("任务执行连续失败次数")
    private int executionFailedTime;

    @ApiModelProperty("结束时间")
    private long endTime;

    @ApiModelProperty("等待时间")
    private long waitTime;

    public void resetWaitTime() {
        endTime = 0;
        waitTime = 0;
    }

    public boolean canRun() {
        return System.currentTimeMillis() - endTime >= waitTime;
    }

    //任务初始化
    public void init(StateDiagram stateDiagram, Map<Integer, OperationBean> operationBeanMap, List<Integer> list) {
        this.stateDiagram = stateDiagram;
        this.operationBeanMap = operationBeanMap;
        this.operationQue = new LinkedList<>();

        list.forEach(item -> {
            addRunOperation(item);
        });
        this.endTime = 0 ;
        this.waitTime = 0 ;
        this.targetOperationSeq = 0;
        this.targetStateSeq = 0;
        this.currentStateSeq = -1;
        this.status = TaskStatusEnum.MISS_STATES;
    }

    public void addRunOperation(Integer operationId) {
        operationQue.push(CglibUtil.copy(operationBeanMap.get(operationId), OperationBean.class));
        if(this.status == TaskStatusEnum.TERMINAL){
            this.status = TaskStatusEnum.MISS_STATES;
        }
    }

    //任务执行失败
    public void executionFailed() {
        executionFailedTime++;
        if (executionFailedTime == 5) {
            //连续运行失败则标志任务为停止状态
            status = TaskStatusEnum.TERMINAL;
        }
    }

    //任务执行成功
    public void executionSuccess() {
        executionFailedTime = 0;
    }
}
